package com.kafka.core;

import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

import net.sf.json.JSONObject;
import org.apache.log4j.PropertyConfigurator;
import com.kafka.enumtype.MsgType;
import com.kafka.util.BaseUtil;
import com.kafka.util.HttpUtil;

public class BaseProducer extends BaseClass{
	
	public static String appID;
	public static String SECRETKEY;
	//用户平台校验路径
	public static String USERVALIDURI;
	//ICCARD平台校验路径
	public static String ACCOUNTQUERYURI;
	public String ENCODE;

	public BaseProducer() {
		Properties properties = new Properties();
		try {
			properties.load(ClassLoader
					.getSystemResourceAsStream("sysconfig.properties"));
			ENCODE = properties.getProperty("encode");
			USERVALIDURI = properties.getProperty("user_valid_uri");
			ACCOUNTQUERYURI = properties.getProperty("account_query_uri");
			appID = properties.getProperty("AppID");
			SECRETKEY = properties.getProperty("SecretKey");
		} catch (IOException e) {
			e.printStackTrace();
		}
		PropertyConfigurator.configure("config/log4j.properties");
	}
	
	/**
	 * 通过平台校验用户是否存在
	 * @param message
	 * @return
	 */
	protected static JSONObject validUserWithPlatform(JSONObject message){
		try {
			JSONObject datas = message.getJSONObject("datas");
			JSONObject validParams = new JSONObject();
			validParams.put("uuid", datas.getString("uuid"));
			validParams.put("loginname", datas.getString("loginname"));
			validParams.put("agedness_card", datas.getString("agedness_card"));
			validParams.put("mobile", datas.getString("mobile"));
			validParams.put("email", datas.getString("email"));
			validParams.put("sid", datas.getString("sid"));
			validParams.put("true_name", datas.getString("true_name"));
			String json = HttpUtil.doPost(USERVALIDURI, validParams.toString(),appID,SECRETKEY);
			return JSONObject.fromObject(json);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 向平台请求卡信息
	 * @param params
	 * @return
	 */
	protected static JSONObject queryIccardWithPlatform(JSONObject params){
		try {
			String json = HttpUtil.doPost(ACCOUNTQUERYURI, params.toString(),appID,SECRETKEY);
			return JSONObject.fromObject(json);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 创建跨平台message
	 * @param datas
	 * @param msgType
	 * @return
	 */
	protected JSONObject createDCMessage(JSONObject datas,MsgType msgType){
		JSONObject message = new JSONObject();
		message.put("msgtype", msgType);
		UUID msgid = UUID.randomUUID();
		message.put("msgid", msgid.toString());
		message.put("datas", rebuildJSON(datas));
		message.put("createtime",BaseUtil.getDate());
		return message;
	}
	
	/**
	 * 追加加appid 和 secretkey
	 * @param message
	 * @return
	 */
	protected JSONObject addAppidAndSecretkey(JSONObject message){
		// 追加appid和secretkey
		message.put("appid", appID);
		message.put("secretkey", SECRETKEY);
		return message;
	}
}
